package com.xigua.a02;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;

public class TestBeanFactory {

    public static void main(String[] args) {

        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        //bean的定义 (class、scope、初始化、销毁)
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(Config.class).setScope("singleton").getBeanDefinition();

        beanFactory.registerBeanDefinition("config",beanDefinition);

        //BeanFactory 后处理主要功能，补充了一些bean的定义
        AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory);

        Collection<BeanFactoryPostProcessor> values = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class).values();
        values.stream().forEach(beanFactoryPostProcessor -> {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        });

        for (String name : beanFactory.getBeanDefinitionNames()) {
            System.out.println(name);
        }

        System.out.println(beanFactory.getBean("bean2"));

    }

    @Configuration
    static class Config{

        @Bean
        public Bean1 getBean1(){
            return new Bean1();
        }

        @Bean("bean2")
        public Bean2 getBean2(){
            return new Bean2();
        }

    }

    static class Bean1 {
        private static final Logger logger = LoggerFactory.getLogger(Bean1.class);
        public Bean1() {
            logger.debug("Bean1 构造器");
        }

        public Bean2 getBean2() {
            return bean;
        }

        private Bean2 bean;


    }

    static class Bean2{
        private static final Logger logger = LoggerFactory.getLogger(Bean2.class);

        public Bean2() {
            logger.debug("Bean2构造器");
        }
    }

}
